<?php

namespace Managers;

class Block extends BaseManager
{
    const TABLE = '\Catalog\Block';
    protected $__table = self::TABLE;
    protected $cacheNames = array('widgets', 'active_widgets');
    const TIME_IN_CACHE = 3600; // 1 hour

    protected function createQueryBuilder()
    {
        $qb = $this->_em->createQueryBuilder()
            ->select('bl')
            ->from(self::TABLE, 'bl')
            ->andWhere('bl.isDel = 0');
        return $qb;
    }

    public function getList()
    {
        $cacheName = $this->cacheNames[0];
        $res = $this->_getCacheManager()->load($cacheName);
        if (!$res) {
            $qb = $this->createQueryBuilder()
                ->orderBy('bl.sortOrder', "DESC");
            $res = $qb->getQuery()->getArrayResult();
            $this->_getCacheManager()->save($res, $cacheName, array(), self::TIME_IN_CACHE);
        }
        return $res;
    }

    public function getActiveList()
    {
        $cacheName = $this->cacheNames[1];
        $res = $this->_getCacheManager()->load($cacheName);
        if (!$res) {
            $qb = $this->createQueryBuilder()
                ->andWhere('bl.isActive = 1')
                ->orderBy('bl.sortOrder', 'DESC');
            $res = $qb->getQuery()->getArrayResult();
            $this->_getCacheManager()->save($res, $cacheName, array(), self::TIME_IN_CACHE);
        }
        return $res;
    }

    public function move($orders, $enabled)
    {
        if (!is_array($orders)) {
            return false;
        }
        $max = count($orders);
        $entities = $this->findAll();
        foreach ($orders as $key => $order) {
            foreach ($entities as $entity) {
                if ($entity->getId() == $order) {
                    $entity->setSortOrder($max - $key);
                    if (isset($enabled[$entity->getId()])) {
                        $entity->setIsActive(true);
                    } else {
                        $entity->setIsActive(false);
                    }
                    $this->_em->persist($entity);
                }
            }
        }
        $this->flush();
        return true;
    }
}
